//
//  AddOrderViewController.swift
//  AmountBody
//
//  Created by Qiu Jishuai on 2018/2/1.
//  Copyright © 2018年 RCMTM. All rights reserved.
//

import UIKit
import ReactiveCocoa
import ReactiveSwift

class AddOrderViewController: BasePresentedViewController {

    //MARK: - Properties
    //表头
    let formHeader = FormRowView()

    lazy var tableView: UITableView = {
        let tableView = UITableView.adjustedTableView(viewController: self)
        tableView.delegate = self
        tableView.dataSource = self
        tableView.allowsSelection = false
        tableView.separatorStyle = .none
        tableView.estimatedRowHeight = Cell.Metric.defaultRowHeight
        tableView.rowHeight = UITableViewAutomaticDimension
        tableView.hideFooter()
        tableView.registerCellClass(with: Cell.self)
        return tableView
    }()

    lazy var switchView: SwitchView = {
        let switchView = SwitchView()
        switchView.titles = ["全部", "普通订单", "物料订单", "返修订单"]
        switchView.indexChangedAction = { (index) in

        }
        return switchView
    }()

    lazy var searchBar: UISearchBar = {
        let searchBar = UISearchBar()
        searchBar.showsBookmarkButton = true
        searchBar.setImage(UIImage(), for: .search, state: .normal)
        searchBar.setImage(#imageLiteral(resourceName: "common_btn_search"), for: .bookmark, state: .normal)
        if searchBar.subviews.count > 0 {
            (searchBar.subviews[0] as? UITextField)?.font = UIFont.systemRegularFont(withSize: 12)
        }
        searchBar.barTintColor = .white
        let image = UIImage(color: .white, size: CGSize(width: 100, height: 22))
        searchBar.setBackgroundImage(UIImage(), for: .any, barMetrics: .default)
        searchBar.tintColor = UIColor.themeRedColor
        searchBar.returnKeyType = .search
        searchBar.placeholder = "请输入订单号, 客户单号, 客户姓名, 面料号等关键词"
        searchBar.addLine(on: .bottom, color: UIColor.themeLineColor, inset: UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0))
        return searchBar
    }()

    lazy var calenderButton: UIButton = {
        let button = UIButton(type: .system)
        button.setImage(#imageLiteral(resourceName: "addorder_btn_calander").alwaysOriginal(), for: .normal)
        button.addTarget(self, action: #selector(showCalender), for: .touchUpInside)
        return button
    }()

    lazy var selectAllButton: UIButton = {
        let button = UIButton(type: .system)
        button.setImage(#imageLiteral(resourceName: "addorder_btn_calander").alwaysOriginal(), for: .normal)
        button.addTarget(self, action: #selector(selectOrDeselectAll), for: .touchUpInside)
        return button
    }()

    let isSelectedAll = MutableProperty(false)

    let scales: [CGFloat] = (0...7).map{ _ in 1 / 9.0 }// [0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1]

    var rowModels: [Cell.RowModel] = []
    var configsArray: [[FormRowView.Config]] = []

    override func viewDidLoad() {
        super.viewDidLoad()

        bgImage = #imageLiteral(resourceName: "img_logistics_bg")
        confirmButtonStyle = .innerBottom
        confirmButton.setTitle("确定", for: .normal)

        selectAllButton.reactive.isSelected <~ isSelectedAll.signal

        contentView.addSubview(searchBar)
        contentView.addSubview(calenderButton)
        contentView.addSubview(switchView)
        contentView.addSubview(formHeader)
        contentView.addSubview(tableView)
        contentView.addSubview(selectAllButton)

        searchBar.mas_makeConstraints { (make) in
            make?.left.right().top().equalTo()(contentView)
            make?.width.equalTo()(contentView)?.multipliedBy()(0.6)
        }

        calenderButton.mas_makeConstraints { (make) in
            make?.right.equalTo()(contentView)
            make?.centerY.equalTo()(searchBar)
        }

        switchView.mas_makeConstraints { (make) in
            make?.top.equalTo()(calenderButton.mas_bottom)?.offset()(5)
            make?.right.equalTo()(contentView)
        }

        formHeader.mas_makeConstraints { (make) in
            make?.top.equalTo()(switchView.mas_bottom)?.offset()(30)
            make?.left.right().equalTo()(contentView)?.offset()(Cell.Metric.defaultRowHeight)
            make?.height.equalTo()(20)
        }

        tableView.mas_makeConstraints { (make) in
            make?.top.equalTo()(formHeader.mas_bottom)
            make?.left.right().equalTo()(contentView)
        }

        selectAllButton.mas_makeConstraints { (make) in
            make?.left.equalTo()(contentView)
            make?.bottom.equalTo()(contentView)
            make?.top.equalTo()(tableView.mas_bottom)?.offset()(30)
        }

        let headerFont = UIFont.systemRegularFont(withSize: 10)
        let titles = ["序号", "订单号", "客户单号", "产品", "面料号", "客户姓名", "下单日期", "交货日期"]
        for _ in 0...10 {
            let configs = titles.enumerated().map({ (index, title) -> FormRowView.Config in
                let str = NSAttributedString(string: title, attributes: [.font: headerFont])
                let config = FormRowView.Config(attributeText: str, width: 30, alignment: .center)
                return config
            })
            configsArray.append(configs)
            let model = Cell.RowModel()
            rowModels.append(model)
        }

        let font2 = UIFont.systemRegularFont(withSize: 10)
        formHeader.configs = titles.enumerated().map({ (index, title) in
            let str = NSAttributedString(string: title, attributes: [.font: font2])
            let config = FormRowView.Config(attributeText: str, width: 30, alignment: .center)
            return config
        })
    }
}

//MARK: - Private method
extension AddOrderViewController {

    @objc private func showCalender() {


    }

    @objc private func selectOrDeselectAll() {
        rowModels.forEach { (model) in
//            model.isSelected
        }
    }
}

extension AddOrderViewController: UITableViewDelegate, UITableViewDataSource {

    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return rowModels.count
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell: Cell = tableView.dequeueReusableCell(for: indexPath)
        let model = rowModels[indexPath.row]
        cell.selectionButton.reactive.isSelected <~ model.isSelected.producer.take(until: cell.reactive.prepareForReuse)
        cell.selectionAction = { (isSelected) in
            model.isSelected.value = !model.isSelected.value
        }
        cell.rowView.configs = configsArray[indexPath.row]
        return cell
    }
}

extension AddOrderViewController {

    class Cell: UITableViewCell {
        typealias SelectionAction = (_ isSelected: Bool) -> Void

        struct RowModel {
            let isSelected = MutableProperty<Bool>(false)
        }

        //MARK: - Constants
        struct Metric {
            static let defaultRowHeight: CGFloat = 42
        }

        let rowView = FormRowView()

        var selectionAction: SelectionAction?
        var rowHeight: CGFloat = Metric.defaultRowHeight

        override func systemLayoutSizeFitting(_ targetSize: CGSize, withHorizontalFittingPriority horizontalFittingPriority: UILayoutPriority, verticalFittingPriority: UILayoutPriority) -> CGSize {
            return CGSize(width: width, height: rowHeight)
        }

        lazy var selectionButton: UIButton = {
            let button = UIButton(type: .system)
            let image = UIImage(by: .white, size: CGSize(width: 16, height: 16), cornerRadius: 8, borderWidth: 1 / UIScreen.main.scale, borderColor: UIColor(hexString: "#979797"), stretch: false)!
            button.setImage(image.alwaysOriginal(), for: .normal)
            button.addTarget(self, action: #selector(selectOrDeselect), for: .touchUpInside)
            return button
        }()

        @objc private func selectOrDeselect(_ sender: UIButton) {
            selectionAction?(sender.isSelected)
        }

        override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
            super.init(style: style, reuseIdentifier: reuseIdentifier)

            contentView.addSubview(selectionButton)
            contentView.addSubview(rowView)

            selectionButton.mas_makeConstraints { (make) in
                make?.left.top().bottom().equalTo()(contentView)
                make?.width.equalTo()(Metric.defaultRowHeight)
            }
            rowView.mas_makeConstraints { (make) in
                make?.top.bottom().equalTo()(contentView)
                make?.left.equalTo()(selectionButton.mas_right)
                make?.right.equalTo()(contentView)
            }
        }

        required init?(coder aDecoder: NSCoder) {
            fatalError("init(coder:) has not been implemented")
        }
    }
}

class FormRowView: UIView {

    struct Config: Equatable {
        let attributeText: NSAttributedString
        let width: CGFloat
        let alignment: NSTextAlignment

        static func ==(lhs: Config, rhs: Config) -> Bool {
            return lhs.attributeText.isEqual(to: rhs.attributeText) &&
            lhs.width == rhs.width
        }
    }

    var labels: [UILabel] = []

    var configs: [Config] = [] {
        didSet {
            let targetCount = configs.count
            while labels.count > targetCount {
                labels.removeLast().removeFromSuperview()
            }
            while labels.count < targetCount {
               let label = UILabel()
                label.numberOfLines = 0
                label.backgroundColor = UIColor.random()
                labels.append(label)
                addSubview(label)
            }
            //设置文字
            for (index, config) in configs.enumerated() {
                let label = labels[index]
                label.attributedText = config.attributeText
                label.textAlignment = config.alignment
                label.mas_remakeConstraints({ (make) in
                    make?.top.bottom().equalTo()(self)
                    make?.width.equalTo()(config.width)
                    if index == 0 {
                        make?.left.equalTo()(self)
                    } else {
                        make?.left.equalTo()(labels[index - 1].mas_right)
                    }
                })
            }
        }
    }
}
